#include "SysInfo.h"

int SysInfo::getDevIpAddr(char IpBuff[],int IpBuffsize)
{
    // 使用gethosybyname获取本机地址，会出错，获取百度域名对应的IP可以

    // 使用ioctl
    int sockfd;
    struct ifconf ifconf;
    struct ifreq *ifreq;
    char buf[512];//缓冲区
    //初始化ifconf
    ifconf.ifc_len =512;
    ifconf.ifc_buf = buf;
    if ((sockfd =socket(AF_INET,SOCK_DGRAM,0))<0)
    {
        printf("socket eoor\n");
        exit(1);
    }
    ioctl(sockfd, SIOCGIFCONF, &ifconf); //获取所有接口信息

    //接下来一个一个的获取IP地址
    ifreq = (struct ifreq*)ifconf.ifc_buf;
    //printf("ifconf.ifc_len:%d\n",ifconf.ifc_len);
    //printf("sizeof (struct ifreq):%d\n",sizeof (struct ifreq));

    for (int i=(ifconf.ifc_len/sizeof (struct ifreq)); i>0; i--)
    {
        if(ifreq->ifr_flags == AF_INET){ //for ipv4
            //printf("name =[%s]\n" , ifreq->ifr_name);
            //printf("local addr = [%s]\n" ,inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr));
            if(strncmp(ifreq->ifr_name,"eth0",4) == 0)
                strncpy(IpBuff,inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr),IpBuffsize);
            ifreq++;
        }
        
    }
    return 0;
}


void SysInfo::getDevName(char buf[],int bufsize)
{
    gethostname(buf,bufsize);
}


void SysInfo::getCurrFreq(char freqBuf[],int bufsize)
{
    char Buf[10];
    #define CPU_CURR_FREQ_FILE "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq"
    if(access(CPU_CURR_FREQ_FILE,F_OK) == 0)
    {
        FILE* fp = fopen(CPU_CURR_FREQ_FILE,"r");
        fread(Buf,1,sizeof(Buf),fp);
        fclose(fp);
    }
    else
    {
        printf("access() error\n");
        freqBuf = NULL;
    }
    strncpy(freqBuf,Buf,bufsize);

    return ;
}

// example 192.168.1.105 = 3232235881 (U32INT) (0xC0 A8 01 69) = (192 168 1 105)
int SysInfo::ipv4Addr2Uint32(char ipAddrStr[])
{
    UNI_U32INT_4UCHAR ipAddr;
    int i;
    printf("original Str = %s\n",ipAddrStr);
    
    sscanf(ipAddrStr,"%hhu.%hhu.%hhu.%hhu",&(ipAddr.UCharData[3]),&(ipAddr.UCharData[2]),&(ipAddr.UCharData[1]),&(ipAddr.UCharData[0]));
    //sscanf(ipAddrStr,"%d.%d.%d.%d",&(ipAddr.UCharData[3]),&(ipAddr.UCharData[2]),&(ipAddr.UCharData[1]),&(ipAddr.UCharData[0]));
    //sscanf(ipAddrStr,"%d.%d.%d.%d",&(ipAddr.UCharData[0]),&(ipAddr.UCharData[1]),&(ipAddr.UCharData[2]),&(ipAddr.UCharData[3]));

    printf("ipv4Addr2Uint32() \n");
    for(i=3;i>=0;i--)
    {
        printf("[%d] = %hhu\t",i,ipAddr.UCharData[i]);
    }
    printf("\n int = %u\n",ipAddr.U32Data);
    
}